var audioPlayer = {
    playAudio: function(filename) {
        var player = document.getElementById('player');
        player.src = '/media/' + filename;
        player.load();
        player.play();
    },
    
    addToPlaylist: function(filename) {
        var list = $('#playlist').find('ul');
        if (list.length == 0) {
            list = $('#playlist').append('<ul></ul>').find('ul');
        }
        list.append('<li>' + filename + '</li>');
    }
};
    
var searchQuery = function() {
    // private methods
    var addPagination = function(totalResultsFound) {
        if (totalResultsFound <= 100)
            return;

        var list = $('#pagination').append('<ul></ul>').find('ul');
                
        for (var i = 0; i < totalResultsFound / 100; i++) {
            var pageNumber =  (i + 1);
            list.append('<li><a href="#">' + pageNumber + '</a></li>');

            list.click(function(e) {
                searchQuery.pageNumber = e.target.innerHTML;
                searchQuery.search();
            });
        }
    }

    var addFacetGroups = function(totalResultsFound, facets) {
        $('#facets').empty();
        
        addFacets(facets['genre'], 'Genre');
        addFacets(facets['performer'], 'Performer');
    }
    
    var addFacets = function(facets, facetType) {
        var list = $('#facets').append('<h2>' + facetType + '</h2><ul id="' + facetType + '-facet"></ul>').find('ul#' + facetType + '-facet');
        if (facets.length <= 0)
            return;

        for (var i = 0; i < facets.length; i++) {
            if (i % 2 == 0) {
                result = facets[i];
                facetCount = facets[i + 1];
                if (facetCount > 0) {
                    list.append('<li><a href="/?q=' + this.query + '&fq=' + facetType + ':' + escape('"' + result + '"') + '">' + result + '</a>&nbsp;(' + facetCount + ')</li>');
                }
            }
        }
    }
    
    var addDebugInfo = function(data) {    
        if(data['debug_info']) {
            $('#debug-info').empty();
            $('#debug-info').append('<div>solr query:  <a href="' +data['debug_info'] + '" target="_blank">' +data['debug_info'] + '</a></div>');
            $('#debug-info').append('<div>total results found:  ' + data['total_results_found'] + '</div>');
        }
    }

    var createRow = function(searchResult, index) {
        var rowClass = (index % 2 == 0) ? "alt-row" : "";

        var row = '<tr class="' + rowClass + '" id="' + searchResult.filename + '">';
        row += '<td class="play"><a class="playAudio" href="#">play</a></td>';
        row += '<td class="queue"><a class="addToPlaylist" href="#">queue</a></td>';
        row += '<td class="title">' + searchResult.title + '</td>';
        row += '<td class="author">' + searchResult.author + '</td>';
        row += '<td class="album">' + searchResult.album + '</td>';
        row += '</tr>';
        
        return row;
    }
    
    return {
        debugFlag: '',
        query: '',
        facetQuery: '',
        pageNumber: 1,
            
        buildSearchUrl: function() {
            var url = '/search?query=' + this.query + '&page=' + this.pageNumber;
            if (this.facetQuery) {
                url += '&facet=' + this.facetQuery;
            }
            if (this.debugFlag !='') {
                url += '&' + this.debugFlag;
            }
            return url;
        },
        
        search: function() {
            $.getJSON(this.buildSearchUrl(), function(data) {
                $('#results').empty();
                $('#pagination').empty();
                $('#facets').empty();
                
                var query = '';
                if (data['query']) {
                    query = data['query'];
                }
                
                if (data['search_results'].length > 0) {
                    var results = $('#results').append('<table><tr><th></th><th></th><th>Title</th><th>Artist</th><th>Album</th></tr></table>').find('table');
                    var result, row;
                    
                    for (var i = 0; i < data['search_results'].length; i++) {
                        result = data['search_results'][i];
                        row = createRow(result, i);

                        results.append(row);
                    }
                    
                    results.click(function(e) {
                        var action = e.target.className; 
                        var filename = e.target.parentNode.parentNode.id;

                        audioPlayer[action](filename);
                    });
                }

                addPagination(data['total_results_found']);
                addFacetGroups(data['total_results_found'], data['facets']);
                addDebugInfo(data);
            });
        }
    };
}();


$(document).ready(function () {
    $('#q').focus();

    var querystring = window.location.search.replace('?', '').split('&');
    for (var i = 0; i < querystring.length; i++) {
        var nameValue = querystring[i].split('=');
        
        if (nameValue[0] == 'debug') {
            searchQuery.debugFlag = querystring[i];
        }

        if (nameValue[0] == 'q') {
            searchQuery.query = nameValue[1];
             $('#q').val(unescape(searchQuery.query));
        }
        
        if (nameValue[0] == 'fq') {
            searchQuery.facetQuery = nameValue[1];
        }
        
        if (nameValue[0] == 'page') {
            searchQuery.pageNumber = nameValue[1];
        }
    }

    searchQuery.search();
    
    $('#search-form').submit(function () {
        searchQuery.query = $('#q').val();
        searchQuery.facetQuery = '';
        searchQuery.pageNumber = 1;
        searchQuery.search();

        return false;
    });
});
